using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using System;

public struct JoyStickData
{
    public Vector2 dir;//方向
    public float radius;//移动的半径

    public JoyStickData(Vector2 v,float r)
    {
        this.dir = v;
        this.radius = r;
    }
    public Vector2 GetPos()
    {
        return dir * radius;
    }
}

public class JoyStick : MonoBehaviour,IPointerDownHandler,IPointerUpHandler,IDragHandler
{
    public RectTransform bound;//外圈
    public RectTransform center;//内圈
    public float radius;//限制半径

    private JoyStickData HandleEventData(PointerEventData eventData)
    {
        Vector2 dir;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(bound,eventData.position,eventData.pressEventCamera,out dir);
        float r = dir.magnitude;
        dir = dir.normalized;
        r = Mathf.Clamp(r,0,radius);
        return new JoyStickData(dir,r);
    }

    public void OnDrag(PointerEventData eventData)
    {
        var data = HandleEventData(eventData);
        center.localPosition = data.GetPos();
        onJoysticMove(data.dir,data.radius);
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        var data = HandleEventData(eventData);
        center.localPosition = data.GetPos();
        onJoysticDown(data.dir, data.radius);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        var data = HandleEventData(eventData);
        center.localPosition = Vector2.zero;
        onJoysticUp(data.dir, data.radius);
    }

    public virtual void onJoysticDown(Vector2 v, float r)
    {

    }
    public virtual void onJoysticUp(Vector2 v, float r)
    {

    }
    public virtual void onJoysticMove(Vector2 v, float r)
    {

    }
}
